package utils;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.impl.EditorImpl;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class FileUtil {

    /**
     * 生成
     *
     * @param content 类中的内容
     * @param file    要写入的文件
     */
    public static void writeStringToFile(File file, String content) {
        try {
            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            bw.write(content);
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取当前编辑器打开的最后的一个文件
     *
     * @return 如果未打开，会返回 null
     */
    public static @Nullable
    EditorImpl getNowEditorFile(AnActionEvent event) {
        Editor editor = event.getData(PlatformDataKeys.EDITOR_EVEN_IF_INACTIVE);
        if (editor instanceof EditorImpl) {
            return (EditorImpl) editor;
        }
        return null;
    }

    /**
     * 获取当前文件父级树中指定名字的父级文件夹
     *
     * @param nowFile          当前文件
     * @param targetParentName 目标父级文件夹名字
     * @return 如果找不到会返回null
     */
    public static @Nullable
    VirtualFile getTargetParent(VirtualFile nowFile, String... targetParentName) {
        while ((nowFile = nowFile.getParent()) != null) {
            VirtualFile t = nowFile;
            int p = 0;
            while (t != null && p < targetParentName.length && t.getName().equals(targetParentName[p++])) {
                t = t.getParent();
            }
            if (p >= targetParentName.length) {
                return nowFile;
            }
        }
        return null;
    }

    /**
     * 获取当前文件夹指定目录下的目标文件
     *
     * @param parentFile     当前父级
     * @param targetFileName 目标文件名，须带有后缀
     * @param path           路径
     * @return 如果找不到会返回 null
     */
    public static VirtualFile findFileInPath(@NotNull VirtualFile parentFile, String targetFileName, String... path) {
        for (String p : path) {
            parentFile = parentFile.findChild(p);
            if (parentFile == null) {
                return null;
            }
        }
        return parentFile.findChild(targetFileName);
    }
}
